#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
SQL目标代码生成器
基于语义分析产生的四元式中间代码生成目标代码

实现功能：
1. 分析基本块结构的标志
2. 做寄存器的分配和内存的存储工作，产生目标代码
3. 执行计划生成（类似数据库查询优化）
4. 生成类似汇编的目标代码
"""

from typing import Dict, List, Set, Tuple, Optional, Union, Any
from enum import Enum
import copy
from SemanticAnalysis import Quadruple, SymbolTableEntry
from ErrorCorrection import SmartErrorCorrector, ErrorInfo


class RegisterType(Enum):
    """寄存器类型枚举"""
    R1 = "R1"      # 通用寄存器1
    R2 = "R2"      # 通用寄存器2
    R3 = "R3"      # 通用寄存器3
    R4 = "R4"      # 通用寄存器4
    ACC = "ACC"    # 累加器
    BASE = "BASE"  # 基址寄存器


class TargetInstruction:
    """目标指令类"""
    
    def __init__(self, opcode: str, operand1: str = "", operand2: str = "", operand3: str = ""):
        self.opcode = opcode        # 操作码
        self.operand1 = operand1    # 操作数1
        self.operand2 = operand2    # 操作数2  
        self.operand3 = operand3    # 操作数3
    
    def __str__(self):
        operands = []
        if self.operand1:
            operands.append(self.operand1)
        if self.operand2:
            operands.append(self.operand2)
        if self.operand3:
            operands.append(self.operand3)
        
        if operands:
            return f"{self.opcode:<8} {', '.join(operands)}"
        else:
            return f"{self.opcode}"
    
    def __repr__(self):
        return self.__str__()


class RegisterDescriptor:
    """寄存器描述符"""
    
    def __init__(self):
        # 寄存器中存储的变量
        self.register_contents: Dict[str, Set[str]] = {
            "R1": set(), "R2": set(), "R3": set(), "R4": set(),
            "ACC": set(), "BASE": set()
        }
        
        # 变量存储的寄存器
        self.variable_locations: Dict[str, Set[str]] = {}
    
    def allocate_register(self, variable: str, preferred_reg: str = None) -> str:
        """分配寄存器给变量"""
        # 如果变量已经在寄存器中，返回该寄存器
        if variable in self.variable_locations:
            for reg in self.variable_locations[variable]:
                if reg in self.register_contents:
                    return reg
        
        # 选择寄存器
        if preferred_reg and not self.register_contents[preferred_reg]:
            selected_reg = preferred_reg
        else:
            # 选择空闲寄存器
            for reg in ["R1", "R2", "R3", "R4"]:
                if not self.register_contents[reg]:
                    selected_reg = reg
                    break
            else:
                # 所有寄存器都被占用，选择R1（简单策略）
                selected_reg = "R1"
                self.register_contents["R1"].clear()
        
        # 更新描述符
        self.register_contents[selected_reg] = {variable}
        if variable not in self.variable_locations:
            self.variable_locations[variable] = set()
        self.variable_locations[variable].add(selected_reg)
        
        return selected_reg
    
    def free_register(self, register: str):
        """释放寄存器"""
        if register in self.register_contents:
            # 清除变量位置信息
            for var in self.register_contents[register]:
                if var in self.variable_locations:
                    self.variable_locations[var].discard(register)
            self.register_contents[register].clear()
    
    def get_variable_register(self, variable: str) -> Optional[str]:
        """获取变量所在的寄存器"""
        if variable in self.variable_locations:
            for reg in self.variable_locations[variable]:
                if variable in self.register_contents[reg]:
                    return reg
        return None


class CodeGenerator:
    """目标代码生成器"""
    
    def __init__(self):
        # 目标指令序列
        self.target_code: List[TargetInstruction] = []
        
        # 寄存器描述符
        self.register_desc = RegisterDescriptor()
        
        # 内存地址计数器
        self.memory_counter = 1000
        
        # 变量内存地址映射
        self.variable_memory: Dict[str, int] = {}
        
        # 标签计数器
        self.label_counter = 0
        
        # 错误列表
        self.errors: List[str] = []
    
    def generate_label(self) -> str:
        """生成标签"""
        self.label_counter += 1
        return f"L{self.label_counter}"
    
    def allocate_memory(self, variable: str) -> int:
        """为变量分配内存地址"""
        if variable not in self.variable_memory:
            self.variable_memory[variable] = self.memory_counter
            self.memory_counter += 4  # 假设每个变量占4字节
        return self.variable_memory[variable]
    
    def emit_instruction(self, opcode: str, operand1: str = "", operand2: str = "", operand3: str = ""):
        """生成目标指令"""
        instruction = TargetInstruction(opcode, operand1, operand2, operand3)
        self.target_code.append(instruction)
        return len(self.target_code) - 1
    
    def generate_code(self, quadruples: List[Quadruple], symbol_table: Dict[str, SymbolTableEntry]) -> Tuple[List[TargetInstruction], List[str]]:
        """
        目标代码生成主函数
        返回: (目标指令列表, 错误列表)
        """
        print("\n=== 开始目标代码生成 ===")
        
        # 重置状态
        self.target_code = []
        self.register_desc = RegisterDescriptor()
        self.variable_memory = {}
        self.memory_counter = 1000
        self.label_counter = 0
        self.errors = []
        
        # 生成程序头部
        self._generate_program_header()
        
        # 分析基本块
        basic_blocks = self._analyze_basic_blocks(quadruples)
        
        # 为每个基本块生成代码
        for block_id, block in enumerate(basic_blocks):
            print(f"处理基本块 {block_id + 1}...")
            self._generate_block_code(block, symbol_table)
        
        # 生成程序尾部
        self._generate_program_footer()
        
        # 打印结果
        self._print_results()
        
        return self.target_code, self.errors
    
    def _generate_program_header(self):
        """生成程序头部"""
        self.emit_instruction("START:", "", "", "")
        self.emit_instruction("; SQL查询执行计划开始")
        self.emit_instruction("INIT", "BASE", "#1000", "")  # 初始化基址寄存器
    
    def _generate_program_footer(self):
        """生成程序尾部"""
        self.emit_instruction("OUTPUT", "结果集")
        self.emit_instruction("HALT", "", "", "")
        self.emit_instruction("END:")
    
    def _analyze_basic_blocks(self, quadruples: List[Quadruple]) -> List[List[Quadruple]]:
        """分析基本块结构"""
        if not quadruples:
            return []
        
        # 简单策略：将所有四元式作为一个基本块
        # 在更复杂的实现中，可以根据跳转指令等划分基本块
        return [quadruples]
    
    def _generate_block_code(self, block: List[Quadruple], symbol_table: Dict[str, SymbolTableEntry]):
        """为基本块生成代码"""
        for quad in block:
            self._translate_quadruple(quad, symbol_table)
    
    def _translate_quadruple(self, quad: Quadruple, symbol_table: Dict[str, SymbolTableEntry]):
        """翻译单个四元式"""
        print(f"翻译四元式: {quad}")
        
        # 跳过优化器生成的空操作
        if quad.op == "NOP":
            return
        
        if quad.op == "FROM":
            self._translate_from(quad)
        elif quad.op == "FROM_FILTERED":
            self._translate_from_filtered(quad)
        elif quad.op == "SELECT":
            self._translate_select(quad)
        elif quad.op == "WHERE":
            self._translate_where(quad)
        elif quad.op == "CREATE":
            self._translate_create(quad)
        elif quad.op == "COLUMN":
            self._translate_column(quad)
        elif quad.op == "INSERT":
            self._translate_insert(quad)
        elif quad.op == "DELETE":
            self._translate_delete(quad)
        elif quad.op == "UPDATE":
            self._translate_update(quad)
        elif quad.op == "DROP":
            self._translate_drop(quad)
        elif quad.op == "USE":
            self._translate_use(quad)
        elif quad.op == "SET":
            self._translate_set(quad)
        elif quad.op == "JOIN":
            self._translate_join(quad)
        elif quad.op == "JOIN_FILTERED":
            self._translate_join_filtered(quad)
        elif quad.op == "ORDER":
            self._translate_order(quad)
        elif quad.op == "GROUP":
            self._translate_group(quad)
        elif quad.op == "LIMIT":
            self._translate_limit(quad)
        elif quad.op == "UNION":
            self._translate_union(quad)
        elif quad.op == "AGGREGATE":
            self._translate_aggregate(quad)
        elif quad.op == "HAVING":
            self._translate_having(quad)
        elif quad.op == "GRANT":
            self._translate_grant(quad)
        elif quad.op == "CREATE_DATABASE":
            self._translate_create_database(quad)
        elif quad.op == "DROP_DATABASE":
            self._translate_drop_database(quad)
        elif quad.op == "LIST_DATABASES":
            self._translate_list_databases(quad)
        elif quad.op == "CREATE_USER":
            self._translate_create_user(quad)
        elif quad.op == "DROP_USER":
            self._translate_drop_user(quad)
        elif quad.op == "LIST_USERS":
            self._translate_list_users(quad)
        elif quad.op == "RESULT":
            self._translate_result(quad)
        elif quad.op in [">", "<", "=", ">=", "<=", "!=", "LIKE"]:
            self._translate_comparison(quad)
        elif quad.op == "=":
            self._translate_assign(quad)
        elif quad.op == "AND":
            self._translate_logical_and(quad)
        elif quad.op == "OR":
            self._translate_logical_or(quad)
        else:
            self.errors.append(f"未知的四元式操作: {quad.op}")
    
    def _translate_from(self, quad: Quadruple):
        """翻译FROM操作"""
        table_name = quad.arg1
        result_temp = quad.result
        
        # 生成表扫描指令
        self.emit_instruction("; 打开表")
        self.emit_instruction("OPEN", table_name, "", "")
        
        # 为结果分配寄存器
        reg = self.register_desc.allocate_register(result_temp, "BASE")
        
        # 生成顺序扫描指令  
        self.emit_instruction("SCAN", table_name, "->", reg)
        
        # 分配内存地址
        addr = self.allocate_memory(result_temp)
        self.emit_instruction("STORE", reg, f"#{addr}", "")
    
    def _translate_from_filtered(self, quad: Quadruple):
        """翻译优化后的FROM_FILTERED操作（谓词下推）"""
        table_name = quad.arg1
        filter_condition = quad.arg2
        result_temp = quad.result
        
        # 生成表扫描指令
        self.emit_instruction("; 打开表（带过滤条件）")
        self.emit_instruction("OPEN", table_name, "", "")
        
        # 为结果分配寄存器
        reg = self.register_desc.allocate_register(result_temp, "BASE")
        
        # 生成带过滤的扫描指令
        self.emit_instruction("SCAN_FILTERED", table_name, filter_condition, reg)
        
        # 分配内存地址
        addr = self.allocate_memory(result_temp)
        self.emit_instruction("STORE", reg, f"#{addr}", "")
    
    def _translate_select(self, quad: Quadruple):
        """翻译SELECT操作"""
        column_name = quad.arg1
        table_ref = quad.arg2
        result_temp = quad.result
        
        # 获取表引用的寄存器
        table_reg = self.register_desc.get_variable_register(table_ref)
        if not table_reg:
            table_reg = self.register_desc.allocate_register(table_ref)
            addr = self.variable_memory.get(table_ref, self.allocate_memory(table_ref))
            self.emit_instruction("LOAD", f"#{addr}", table_reg, "")
        
        # 为结果分配寄存器
        result_reg = self.register_desc.allocate_register(result_temp)
        
        # 生成投影指令
        if column_name == "*":
            self.emit_instruction("FILTER", "*", "->", result_reg)
        else:
            self.emit_instruction("FILTER", f"{table_ref}.{column_name}", "->", result_reg)
        
        # 生成投影指令
        self.emit_instruction("PROJECT", f"{table_ref}.{column_name}", "->", result_reg)
        
        # 存储结果
        addr = self.allocate_memory(result_temp)
        self.emit_instruction("STORE", result_reg, f"#{addr}", "")
    
    def _translate_where(self, quad: Quadruple):
        """翻译WHERE条件"""
        condition = quad.arg1
        table_ref = quad.arg2
        result_temp = quad.result
        
        # 获取表引用寄存器
        table_reg = self.register_desc.get_variable_register(table_ref)
        if not table_reg:
            table_reg = self.register_desc.allocate_register(table_ref)
        
        # 为结果分配寄存器
        result_reg = self.register_desc.allocate_register(result_temp)
        
        # 生成条件过滤指令
        self.emit_instruction("FILTER", condition, "->", result_reg)
        
        # 存储结果
        addr = self.allocate_memory(result_temp)
        self.emit_instruction("STORE", result_reg, f"#{addr}", "")
    
    def _translate_comparison(self, quad: Quadruple):
        """翻译比较操作"""
        left_operand = quad.arg1
        right_operand = quad.arg2
        result_temp = quad.result
        operator = quad.op
        
        # 为操作数分配寄存器
        left_reg = self.register_desc.allocate_register(f"temp_left")
        right_reg = self.register_desc.allocate_register(f"temp_right")
        
        # 加载操作数
        if left_operand.isdigit():
            self.emit_instruction("LOAD", f"#{left_operand}", left_reg, "")
        else:
            addr = self.variable_memory.get(left_operand, self.allocate_memory(left_operand))
            self.emit_instruction("LOAD", f"#{addr}", left_reg, "")
        
        if right_operand.isdigit():
            self.emit_instruction("LOAD", f"#{right_operand}", right_reg, "")
        else:
            addr = self.variable_memory.get(right_operand, self.allocate_memory(right_operand))
            self.emit_instruction("LOAD", f"#{addr}", right_reg, "")
        
        # 生成比较指令
        if operator == ">":
            self.emit_instruction("CMP", left_reg, right_reg, "")
            self.emit_instruction("JG", "TRUE_LABEL", "", "")
        elif operator == "<":
            self.emit_instruction("CMP", left_reg, right_reg, "")
            self.emit_instruction("JL", "TRUE_LABEL", "", "")
        elif operator == "=":
            self.emit_instruction("CMP", left_reg, right_reg, "")
            self.emit_instruction("JE", "TRUE_LABEL", "", "")
        elif operator == ">=":
            self.emit_instruction("CMP", left_reg, right_reg, "")
            self.emit_instruction("JGE", "TRUE_LABEL", "", "")
        elif operator == "<=":
            self.emit_instruction("CMP", left_reg, right_reg, "")
            self.emit_instruction("JLE", "TRUE_LABEL", "", "")
        elif operator == "!=":
            self.emit_instruction("CMP", left_reg, right_reg, "")
            self.emit_instruction("JNE", "TRUE_LABEL", "", "")
        elif operator == "LIKE":
            self.emit_instruction("LIKE", left_reg, right_reg, "")
            self.emit_instruction("JT", "TRUE_LABEL", "", "")  # Jump if True
        
        # 释放临时寄存器
        self.register_desc.free_register(left_reg)
        self.register_desc.free_register(right_reg)
    
    def _translate_assign(self, quad: Quadruple):
        """翻译赋值操作"""
        source = quad.arg1
        target = quad.result
        
        # 为目标分配寄存器
        target_reg = self.register_desc.allocate_register(target)
        
        # 生成赋值指令
        if source.isdigit():
            self.emit_instruction("LOAD", f"#{source}", target_reg, "")
        else:
            source_reg = self.register_desc.get_variable_register(source)
            if source_reg:
                self.emit_instruction("MOVE", source_reg, target_reg, "")
            else:
                addr = self.variable_memory.get(source, self.allocate_memory(source))
                self.emit_instruction("LOAD", f"#{addr}", target_reg, "")
        
        # 存储到内存
        addr = self.allocate_memory(target)
        self.emit_instruction("STORE", target_reg, f"#{addr}", "")
    
    def _translate_result(self, quad: Quadruple):
        """翻译结果操作"""
        result_var = quad.arg1
        
        # 生成结果输出指令
        self.emit_instruction("; 输出结果集")
        
        if result_var != "-":
            result_reg = self.register_desc.get_variable_register(result_var)
            if not result_reg:
                result_reg = self.register_desc.allocate_register(result_var)
                addr = self.variable_memory.get(result_var, self.allocate_memory(result_var))
                self.emit_instruction("LOAD", f"#{addr}", result_reg, "")
            
            self.emit_instruction("OUTPUT", result_reg, "", "")
        else:
            self.emit_instruction("OUTPUT", "结果集", "", "")
    
    def _translate_create(self, quad: Quadruple):
        """翻译CREATE操作"""
        table_name = quad.arg1
        result_temp = quad.result
        
        # 生成创建表指令
        self.emit_instruction("; 创建表")
        self.emit_instruction("CREATE_TABLE", table_name, "", "")
        
        # 为结果分配寄存器
        reg = self.register_desc.allocate_register(result_temp, "BASE")
        
        # 生成表引用指令
        self.emit_instruction("TABLE_REF", table_name, "->", reg)
        
        # 分配内存地址
        addr = self.allocate_memory(result_temp)
        self.emit_instruction("STORE", reg, f"#{addr}", "")
    
    def _translate_column(self, quad: Quadruple):
        """翻译COLUMN操作"""
        column_name = quad.arg1
        column_type = quad.arg2
        table_temp = quad.result
        
        # 获取表引用的寄存器
        table_reg = self.register_desc.get_variable_register(table_temp)
        if not table_reg:
            table_reg = self.register_desc.allocate_register(table_temp)
            addr = self.variable_memory.get(table_temp, self.allocate_memory(table_temp))
            self.emit_instruction("LOAD", f"#{addr}", table_reg, "")
        
        # 生成列定义指令
        self.emit_instruction("ADD_COLUMN", f"{column_name}:{column_type}", table_reg, "")
    
    def _translate_insert(self, quad: Quadruple):
        """翻译INSERT操作"""
        table_name = quad.arg1
        result_temp = quad.result
        
        # 生成插入指令
        self.emit_instruction("; 插入数据")
        self.emit_instruction("INSERT_INTO", table_name, "", "")
        
        # 为结果分配寄存器
        reg = self.register_desc.allocate_register(result_temp, "R1")
        
        # 生成插入操作指令
        self.emit_instruction("PREPARE_INSERT", table_name, "->", reg)
        
        # 分配内存地址
        addr = self.allocate_memory(result_temp)
        self.emit_instruction("STORE", reg, f"#{addr}", "")
    
    def _translate_delete(self, quad: Quadruple):
        """翻译DELETE操作"""
        where_temp = quad.arg1
        
        # 获取WHERE条件的寄存器
        where_reg = self.register_desc.get_variable_register(where_temp)
        if not where_reg:
            where_reg = self.register_desc.allocate_register(where_temp)
            addr = self.variable_memory.get(where_temp, self.allocate_memory(where_temp))
            self.emit_instruction("LOAD", f"#{addr}", where_reg, "")
        
        # 生成删除指令
        self.emit_instruction("; 删除数据")
        self.emit_instruction("DELETE_ROWS", where_reg, "", "")
        
        # 生成提交指令
        self.emit_instruction("COMMIT", "", "", "")
    
    def _translate_drop(self, quad: Quadruple):
        """翻译DROP TABLE操作"""
        table_name = quad.arg1
        
        # 生成删除表指令
        self.emit_instruction("; 删除表")
        self.emit_instruction("DROP_TABLE", table_name, "", "")
        
        # 为结果分配寄存器（可选）
        reg = self.register_desc.allocate_register("drop_result", "R1")
        
        # 生成表删除确认指令
        self.emit_instruction("CONFIRM_DROP", table_name, "->", reg)
        
        # 分配内存地址
        addr = self.allocate_memory("drop_result")
        self.emit_instruction("STORE", reg, f"#{addr}", "")
        
        # 生成提交指令
        self.emit_instruction("COMMIT", "", "", "")
    
    def _translate_update(self, quad: Quadruple):
        """翻译UPDATE操作"""
        table_name = quad.arg1
        result_temp = quad.result
        
        # 生成更新指令
        self.emit_instruction("; 更新表数据")
        self.emit_instruction("UPDATE_TABLE", table_name, "", "")
        
        # 为结果分配寄存器
        reg = self.register_desc.allocate_register(result_temp, "R1")
        
        # 生成更新准备指令
        self.emit_instruction("PREPARE_UPDATE", table_name, "->", reg)
        
        # 分配内存地址
        addr = self.allocate_memory(result_temp)
        self.emit_instruction("STORE", reg, f"#{addr}", "")
    
    def _translate_set(self, quad: Quadruple):
        """翻译SET操作"""
        set_expression = quad.arg1  # 格式: column=value
        table_ref = quad.arg2
        
        # 解析SET表达式
        if '=' in set_expression:
            column, value = set_expression.split('=', 1)
            
            # 获取表引用的寄存器
            table_reg = self.register_desc.get_variable_register(table_ref)
            if not table_reg:
                table_reg = self.register_desc.allocate_register(table_ref)
                addr = self.variable_memory.get(table_ref, self.allocate_memory(table_ref))
                self.emit_instruction("LOAD", f"#{addr}", table_reg, "")
            
            # 为值分配寄存器
            value_reg = self.register_desc.allocate_register(f"temp_value")
            
            # 加载值
            if value.isdigit() or (value.startswith("'") and value.endswith("'")):
                self.emit_instruction("LOAD", f"#{value}", value_reg, "")
            else:
                value_addr = self.variable_memory.get(value, self.allocate_memory(value))
                self.emit_instruction("LOAD", f"#{value_addr}", value_reg, "")
            
            # 生成SET指令
            self.emit_instruction("SET_COLUMN", f"{table_ref}.{column}", value_reg, "")
            
            # 释放临时寄存器
            self.register_desc.free_register(value_reg)
    
    def _translate_join(self, quad: Quadruple):
        """翻译JOIN操作"""
        join_spec = quad.arg1  # 格式: join_type:table:condition
        left_table_ref = quad.arg2
        result_temp = quad.result
        
        # 解析JOIN规格
        parts = join_spec.split(':', 2)
        if len(parts) == 3:
            join_type, right_table, condition = parts
            
            # 获取左表的寄存器
            left_reg = self.register_desc.get_variable_register(left_table_ref)
            if not left_reg:
                left_reg = self.register_desc.allocate_register(left_table_ref)
                addr = self.variable_memory.get(left_table_ref, self.allocate_memory(left_table_ref))
                self.emit_instruction("LOAD", f"#{addr}", left_reg, "")
            
            # 为右表分配寄存器
            right_reg = self.register_desc.allocate_register(f"temp_right_table")
            self.emit_instruction("SCAN", right_table, "->", right_reg)
            
            # 为结果分配寄存器
            result_reg = self.register_desc.allocate_register(result_temp)
            
            # 生成JOIN指令
            self.emit_instruction(f"; {join_type} JOIN {right_table} ON {condition}")
            if join_type.upper() == "INNER":
                self.emit_instruction("INNER_JOIN", left_reg, right_reg, result_reg)
            elif join_type.upper() == "LEFT":
                self.emit_instruction("LEFT_JOIN", left_reg, right_reg, result_reg)
            elif join_type.upper() == "RIGHT":
                self.emit_instruction("RIGHT_JOIN", left_reg, right_reg, result_reg)
            elif join_type.upper().startswith("FULL"):
                self.emit_instruction("FULL_JOIN", left_reg, right_reg, result_reg)
            else:
                self.emit_instruction("INNER_JOIN", left_reg, right_reg, result_reg)
            
            # 应用连接条件
            self.emit_instruction("JOIN_CONDITION", condition, result_reg, "")
            
            # 存储结果
            addr = self.allocate_memory(result_temp)
            self.emit_instruction("STORE", result_reg, f"#{addr}", "")
            
            # 释放临时寄存器
            self.register_desc.free_register(right_reg)
    
    def _translate_join_filtered(self, quad: Quadruple):
        """翻译优化后的JOIN_FILTERED操作（谓词下推到连接）"""
        join_spec = quad.arg1  # 格式: join_type:table:combined_condition
        left_table_ref = quad.arg2
        result_temp = quad.result
        
        # 解析JOIN规格
        parts = join_spec.split(':', 2)
        if len(parts) == 3:
            join_type, right_table, combined_condition = parts
            
            # 获取左表的寄存器
            left_reg = self.register_desc.get_variable_register(left_table_ref)
            if not left_reg:
                left_reg = self.register_desc.allocate_register(left_table_ref)
                addr = self.variable_memory.get(left_table_ref, self.allocate_memory(left_table_ref))
                self.emit_instruction("LOAD", f"#{addr}", left_reg, "")
            
            # 为右表分配寄存器
            right_reg = self.register_desc.allocate_register(f"temp_right_table")
            self.emit_instruction("SCAN", right_table, "->", right_reg)
            
            # 为结果分配寄存器
            result_reg = self.register_desc.allocate_register(result_temp)
            
            # 生成优化的JOIN指令
            self.emit_instruction(f"; 优化的 {join_type} JOIN {right_table} 带条件: {combined_condition}")
            if join_type.upper() == "INNER":
                self.emit_instruction("INNER_JOIN_FILTERED", left_reg, right_reg, result_reg)
            elif join_type.upper() == "LEFT":
                self.emit_instruction("LEFT_JOIN_FILTERED", left_reg, right_reg, result_reg)
            elif join_type.upper() == "RIGHT":
                self.emit_instruction("RIGHT_JOIN_FILTERED", left_reg, right_reg, result_reg)
            elif join_type.upper().startswith("FULL"):
                self.emit_instruction("FULL_JOIN_FILTERED", left_reg, right_reg, result_reg)
            else:
                self.emit_instruction("INNER_JOIN_FILTERED", left_reg, right_reg, result_reg)
            
            # 应用合并后的连接条件
            self.emit_instruction("APPLY_COMBINED_CONDITION", combined_condition, result_reg, "")
            
            # 存储结果
            addr = self.allocate_memory(result_temp)
            self.emit_instruction("STORE", result_reg, f"#{addr}", "")
            
            # 释放临时寄存器
            self.register_desc.free_register(right_reg)
    
    def _translate_order(self, quad: Quadruple):
        """翻译ORDER BY操作"""
        order_spec = quad.arg1  # 格式: col1:ASC,col2:DESC
        table_ref = quad.arg2
        result_temp = quad.result
        
        # 获取表引用的寄存器
        table_reg = self.register_desc.get_variable_register(table_ref)
        if not table_reg:
            table_reg = self.register_desc.allocate_register(table_ref)
            addr = self.variable_memory.get(table_ref, self.allocate_memory(table_ref))
            self.emit_instruction("LOAD", f"#{addr}", table_reg, "")
        
        # 为结果分配寄存器
        result_reg = self.register_desc.allocate_register(result_temp)
        
        # 生成排序指令
        self.emit_instruction("; 排序操作")
        self.emit_instruction("SORT", order_spec, table_reg, result_reg)
        
        # 存储结果
        addr = self.allocate_memory(result_temp)
        self.emit_instruction("STORE", result_reg, f"#{addr}", "")
    
    def _translate_group(self, quad: Quadruple):
        """翻译GROUP BY操作"""
        group_columns = quad.arg1  # 格式: col1,col2,col3
        table_ref = quad.arg2
        result_temp = quad.result
        
        # 获取表引用的寄存器
        table_reg = self.register_desc.get_variable_register(table_ref)
        if not table_reg:
            table_reg = self.register_desc.allocate_register(table_ref)
            addr = self.variable_memory.get(table_ref, self.allocate_memory(table_ref))
            self.emit_instruction("LOAD", f"#{addr}", table_reg, "")
        
        # 为结果分配寄存器
        result_reg = self.register_desc.allocate_register(result_temp)
        
        # 生成分组指令
        self.emit_instruction("; 分组操作")
        self.emit_instruction("GROUP_BY", group_columns, table_reg, result_reg)
        
        # 存储结果
        addr = self.allocate_memory(result_temp)
        self.emit_instruction("STORE", result_reg, f"#{addr}", "")
    
    def _translate_limit(self, quad: Quadruple):
        """翻译LIMIT操作"""
        limit_value = quad.arg1  # LIMIT的数值
        table_ref = quad.arg2
        result_temp = quad.result
        
        # 获取表引用的寄存器
        table_reg = self.register_desc.get_variable_register(table_ref)
        if not table_reg:
            table_reg = self.register_desc.allocate_register(table_ref)
            addr = self.variable_memory.get(table_ref, self.allocate_memory(table_ref))
            self.emit_instruction("LOAD", f"#{addr}", table_reg, "")
        
        # 为结果分配寄存器
        result_reg = self.register_desc.allocate_register(result_temp)
        
        # 为LIMIT值分配寄存器
        limit_reg = self.register_desc.allocate_register("temp_limit")
        self.emit_instruction("LOAD", f"#{limit_value}", limit_reg, "")
        
        # 生成LIMIT指令
        self.emit_instruction("; 限制结果数量")
        self.emit_instruction("LIMIT_ROWS", limit_reg, table_reg, result_reg)
        
        # 存储结果
        addr = self.allocate_memory(result_temp)
        self.emit_instruction("STORE", result_reg, f"#{addr}", "")
        
        # 释放临时寄存器
        self.register_desc.free_register(limit_reg)
    
    def _translate_use(self, quad: Quadruple):
        """翻译USE操作"""
        database_name = quad.arg1
        
        # 生成使用数据库指令
        self.emit_instruction("; 切换数据库")
        self.emit_instruction("USE_DATABASE", database_name, "", "")
        
        # 为结果分配寄存器（可选）
        reg = self.register_desc.allocate_register("current_db", "BASE")
        
        # 生成数据库上下文设置指令
        self.emit_instruction("SET_CONTEXT", database_name, "->", reg)
        
        # 分配内存地址存储当前数据库信息
        addr = self.allocate_memory("current_db")
        self.emit_instruction("STORE", reg, f"#{addr}", "")
        
        # 生成数据库连接指令
        self.emit_instruction("CONNECT", database_name, "", "")
    
    def _translate_logical_and(self, quad: Quadruple):
        """翻译AND逻辑操作"""
        left_condition = quad.arg1
        right_condition = quad.arg2
        result_temp = quad.result
        
        # 为操作数分配寄存器
        left_reg = self.register_desc.allocate_register(f"temp_left_and")
        right_reg = self.register_desc.allocate_register(f"temp_right_and")
        result_reg = self.register_desc.allocate_register(result_temp)
        
        # 加载左操作数（条件表达式的结果）
        if left_condition.startswith('T'):
            # 临时变量
            left_addr = self.variable_memory.get(left_condition, self.allocate_memory(left_condition))
            self.emit_instruction("LOAD", f"#{left_addr}", left_reg, "")
        else:
            # 字面条件字符串，需要先评估
            self.emit_instruction("EVAL", left_condition, "->", left_reg)
        
        # 加载右操作数
        if right_condition.startswith('T'):
            # 临时变量
            right_addr = self.variable_memory.get(right_condition, self.allocate_memory(right_condition))
            self.emit_instruction("LOAD", f"#{right_addr}", right_reg, "")
        else:
            # 字面条件字符串，需要先评估
            self.emit_instruction("EVAL", right_condition, "->", right_reg)
        
        # 生成AND逻辑指令
        self.emit_instruction("; 逻辑AND操作")
        self.emit_instruction("AND", left_reg, right_reg, result_reg)
        
        # 存储结果
        addr = self.allocate_memory(result_temp)
        self.emit_instruction("STORE", result_reg, f"#{addr}", "")
        
        # 释放临时寄存器
        self.register_desc.free_register(left_reg)
        self.register_desc.free_register(right_reg)
    
    def _translate_logical_or(self, quad: Quadruple):
        """翻译OR逻辑操作"""
        left_condition = quad.arg1
        right_condition = quad.arg2
        result_temp = quad.result
        
        # 为操作数分配寄存器
        left_reg = self.register_desc.allocate_register(f"temp_left_or")
        right_reg = self.register_desc.allocate_register(f"temp_right_or")
        result_reg = self.register_desc.allocate_register(result_temp)
        
        # 加载左操作数（条件表达式的结果）
        if left_condition.startswith('T'):
            # 临时变量
            left_addr = self.variable_memory.get(left_condition, self.allocate_memory(left_condition))
            self.emit_instruction("LOAD", f"#{left_addr}", left_reg, "")
        else:
            # 字面条件字符串，需要先评估
            self.emit_instruction("EVAL", left_condition, "->", left_reg)
        
        # 加载右操作数
        if right_condition.startswith('T'):
            # 临时变量
            right_addr = self.variable_memory.get(right_condition, self.allocate_memory(right_condition))
            self.emit_instruction("LOAD", f"#{right_addr}", right_reg, "")
        else:
            # 字面条件字符串，需要先评估
            self.emit_instruction("EVAL", right_condition, "->", right_reg)
        
        # 生成OR逻辑指令
        self.emit_instruction("; 逻辑OR操作")
        self.emit_instruction("OR", left_reg, right_reg, result_reg)
        
        # 存储结果
        addr = self.allocate_memory(result_temp)
        self.emit_instruction("STORE", result_reg, f"#{addr}", "")
        
        # 释放临时寄存器
        self.register_desc.free_register(left_reg)
        self.register_desc.free_register(right_reg)
    
    def _translate_union(self, quad: Quadruple):
        """翻译UNION操作"""
        union_spec = quad.arg1  # 格式: UNION_TYPE:left_temp:right_temp
        result_temp = quad.result
        
        # 解析UNION规格
        parts = union_spec.split(':', 2)
        if len(parts) == 3:
            union_type, left_temp, right_temp = parts
            
            # 获取左操作数的寄存器
            left_reg = self.register_desc.get_variable_register(left_temp)
            if not left_reg:
                left_reg = self.register_desc.allocate_register(left_temp)
                left_addr = self.variable_memory.get(left_temp, self.allocate_memory(left_temp))
                self.emit_instruction("LOAD", f"#{left_addr}", left_reg, "")
            
            # 获取右操作数的寄存器
            right_reg = self.register_desc.get_variable_register(right_temp)
            if not right_reg:
                right_reg = self.register_desc.allocate_register(right_temp)
                right_addr = self.variable_memory.get(right_temp, self.allocate_memory(right_temp))
                self.emit_instruction("LOAD", f"#{right_addr}", right_reg, "")
            
            # 为结果分配寄存器
            result_reg = self.register_desc.allocate_register(result_temp)
            
            # 生成UNION指令
            self.emit_instruction(f"; {union_type}操作")
            if union_type == "UNION":
                self.emit_instruction("UNION", left_reg, right_reg, result_reg)
                self.emit_instruction("DISTINCT", result_reg, "->", result_reg)  # 去重
            elif union_type == "UNION_ALL":
                self.emit_instruction("UNION_ALL", left_reg, right_reg, result_reg)
            else:
                self.emit_instruction("UNION", left_reg, right_reg, result_reg)
                self.emit_instruction("DISTINCT", result_reg, "->", result_reg)  # 默认去重
            
            # 存储结果
            addr = self.allocate_memory(result_temp)
            self.emit_instruction("STORE", result_reg, f"#{addr}", "")
        else:
            self.errors.append(f"无效的UNION规格: {union_spec}")
    
    def _translate_aggregate(self, quad: Quadruple):
        """翻译聚合函数操作"""
        aggregate_spec = quad.arg1  # 格式: FUNC_TYPE:param
        result_temp = quad.result
        
        # 解析聚合函数规格
        if ':' in aggregate_spec:
            func_type, param = aggregate_spec.split(':', 1)
            
            # 为结果分配寄存器
            result_reg = self.register_desc.allocate_register(result_temp)
            
            # 生成聚合函数指令
            self.emit_instruction(f"; 聚合函数 {func_type}({param})")
            
            if func_type == "COUNT":
                if param == "*":
                    self.emit_instruction("COUNT_ALL", "->", result_reg, "")
                else:
                    # 为参数分配寄存器
                    param_reg = self.register_desc.allocate_register(f"temp_param")
                    if '.' in param:
                        # 限定列名
                        self.emit_instruction("LOAD_COLUMN", param, "->", param_reg)
                    else:
                        # 普通列名
                        self.emit_instruction("LOAD_COLUMN", param, "->", param_reg)
                    
                    self.emit_instruction("COUNT", param_reg, "->", result_reg)
                    self.register_desc.free_register(param_reg)
            
            elif func_type == "SUM":
                # 为参数分配寄存器
                param_reg = self.register_desc.allocate_register(f"temp_param")
                if '.' in param:
                    # 限定列名
                    self.emit_instruction("LOAD_COLUMN", param, "->", param_reg)
                else:
                    # 普通列名
                    self.emit_instruction("LOAD_COLUMN", param, "->", param_reg)
                
                self.emit_instruction("SUM", param_reg, "->", result_reg)
                self.register_desc.free_register(param_reg)
            
            elif func_type == "AVG":
                # 为参数分配寄存器
                param_reg = self.register_desc.allocate_register(f"temp_param")
                if '.' in param:
                    # 限定列名
                    self.emit_instruction("LOAD_COLUMN", param, "->", param_reg)
                else:
                    # 普通列名
                    self.emit_instruction("LOAD_COLUMN", param, "->", param_reg)
                
                self.emit_instruction("AVG", param_reg, "->", result_reg)
                self.register_desc.free_register(param_reg)
            
            elif func_type == "MAX":
                # 为参数分配寄存器
                param_reg = self.register_desc.allocate_register(f"temp_param")
                if '.' in param:
                    # 限定列名
                    self.emit_instruction("LOAD_COLUMN", param, "->", param_reg)
                else:
                    # 普通列名
                    self.emit_instruction("LOAD_COLUMN", param, "->", param_reg)
                
                self.emit_instruction("MAX", param_reg, "->", result_reg)
                self.register_desc.free_register(param_reg)
            
            elif func_type == "MIN":
                # 为参数分配寄存器
                param_reg = self.register_desc.allocate_register(f"temp_param")
                if '.' in param:
                    # 限定列名
                    self.emit_instruction("LOAD_COLUMN", param, "->", param_reg)
                else:
                    # 普通列名
                    self.emit_instruction("LOAD_COLUMN", param, "->", param_reg)
                
                self.emit_instruction("MIN", param_reg, "->", result_reg)
                self.register_desc.free_register(param_reg)
            
            elif func_type == "STDDEV":
                # 为参数分配寄存器
                param_reg = self.register_desc.allocate_register(f"temp_param")
                if '.' in param:
                    # 限定列名
                    self.emit_instruction("LOAD_COLUMN", param, "->", param_reg)
                else:
                    # 普通列名
                    self.emit_instruction("LOAD_COLUMN", param, "->", param_reg)
                
                self.emit_instruction("STDDEV", param_reg, "->", result_reg)
                self.register_desc.free_register(param_reg)
            
            elif func_type == "VARIANCE":
                # 为参数分配寄存器
                param_reg = self.register_desc.allocate_register(f"temp_param")
                if '.' in param:
                    # 限定列名
                    self.emit_instruction("LOAD_COLUMN", param, "->", param_reg)
                else:
                    # 普通列名
                    self.emit_instruction("LOAD_COLUMN", param, "->", param_reg)
                
                self.emit_instruction("VARIANCE", param_reg, "->", result_reg)
                self.register_desc.free_register(param_reg)
            
            else:
                self.errors.append(f"未知的聚合函数类型: {func_type}")
                return
            
            # 存储结果
            addr = self.allocate_memory(result_temp)
            self.emit_instruction("STORE", result_reg, f"#{addr}", "")
            
        else:
            self.errors.append(f"无效的聚合函数规格: {aggregate_spec}")
    
    def _translate_having(self, quad: Quadruple):
        """翻译HAVING操作"""
        having_condition = quad.arg1  # HAVING条件
        table_ref = quad.arg2
        result_temp = quad.result
        
        # 获取表引用的寄存器
        table_reg = self.register_desc.get_variable_register(table_ref)
        if not table_reg:
            table_reg = self.register_desc.allocate_register(table_ref)
            addr = self.variable_memory.get(table_ref, self.allocate_memory(table_ref))
            self.emit_instruction("LOAD", f"#{addr}", table_reg, "")
        
        # 为结果分配寄存器
        result_reg = self.register_desc.allocate_register(result_temp)
        
        # 生成HAVING过滤指令
        self.emit_instruction("; HAVING子句过滤")
        self.emit_instruction("HAVING_FILTER", having_condition, table_reg, result_reg)
        
        # 存储结果
        addr = self.allocate_memory(result_temp)
        self.emit_instruction("STORE", result_reg, f"#{addr}", "")
    
    def _translate_grant(self, quad: Quadruple):
        """翻译GRANT操作"""
        grant_spec = quad.arg1  # 格式: privileges:object_type:object_name:grantees[:grant_option]
        
        # 解析GRANT规格
        parts = grant_spec.split(':', 4)  # 最多分割4次，以支持可选的grant_option
        if len(parts) < 4:
            self.errors.append(f"无效的GRANT规格: {grant_spec}")
            return
        
        privileges, object_type, object_name, grantees = parts[:4]
        grant_option = parts[4] if len(parts) > 4 else None
        
        # 生成GRANT指令序列
        self.emit_instruction("; 权限授予操作")
        self.emit_instruction("GRANT_BEGIN", grant_spec, "", "")
        
        # 为权限列表分配寄存器
        privileges_reg = self.register_desc.allocate_register("temp_privileges")
        self.emit_instruction("LOAD_PRIVILEGES", privileges, "->", privileges_reg)
        
        # 为对象分配寄存器
        object_reg = self.register_desc.allocate_register("temp_object")
        if object_type == "TABLE":
            self.emit_instruction("LOAD_TABLE", object_name, "->", object_reg)
        elif object_type == "DATABASE":
            self.emit_instruction("LOAD_DATABASE", object_name, "->", object_reg)
        else:
            self.emit_instruction("LOAD_OBJECT", f"{object_type}:{object_name}", "->", object_reg)
        
        # 为被授权者列表分配寄存器
        grantees_reg = self.register_desc.allocate_register("temp_grantees")
        self.emit_instruction("LOAD_GRANTEES", grantees, "->", grantees_reg)
        
        # 执行权限授予
        self.emit_instruction("EXECUTE_GRANT", privileges_reg, object_reg, grantees_reg)
        
        # 如果有GRANT选项，处理选项
        if grant_option:
            option_reg = self.register_desc.allocate_register("temp_option")
            self.emit_instruction("LOAD_OPTION", grant_option, "->", option_reg)
            self.emit_instruction("APPLY_GRANT_OPTION", option_reg, grantees_reg, "")
            self.register_desc.free_register(option_reg)
        
        # 提交权限变更
        self.emit_instruction("COMMIT_GRANT", "", "", "")
        
        # 生成审计日志
        audit_reg = self.register_desc.allocate_register("temp_audit")
        self.emit_instruction("AUDIT_LOG", f"GRANT:{privileges}:{object_name}:{grantees}", "->", audit_reg)
        
        # 释放临时寄存器
        self.register_desc.free_register(privileges_reg)
        self.register_desc.free_register(object_reg)
        self.register_desc.free_register(grantees_reg)
        self.register_desc.free_register(audit_reg)
        
        self.emit_instruction("GRANT_END", "", "", "")
    
    def _translate_create_database(self, quad: Quadruple):
        """翻译CREATE DATABASE操作"""
        database_name = quad.arg1
        
        # 生成创建数据库指令序列
        self.emit_instruction("; 创建数据库操作")
        self.emit_instruction("CREATE_DB_BEGIN", database_name, "", "")
        
        # 为数据库分配寄存器
        db_reg = self.register_desc.allocate_register("temp_database")
        self.emit_instruction("INIT_DATABASE", database_name, "->", db_reg)
        
        # 创建数据库目录结构
        self.emit_instruction("CREATE_DB_DIR", database_name, db_reg, "")
        
        # 初始化数据库元数据
        metadata_reg = self.register_desc.allocate_register("temp_metadata")
        self.emit_instruction("INIT_DB_METADATA", database_name, "->", metadata_reg)
        self.emit_instruction("WRITE_DB_METADATA", metadata_reg, db_reg, "")
        
        # 设置数据库权限
        permissions_reg = self.register_desc.allocate_register("temp_permissions")
        self.emit_instruction("SET_DB_PERMISSIONS", "DEFAULT", "->", permissions_reg)
        self.emit_instruction("APPLY_DB_PERMISSIONS", permissions_reg, db_reg, "")
        
        # 提交数据库创建
        self.emit_instruction("COMMIT_CREATE_DB", db_reg, "", "")
        
        # 生成审计日志
        audit_reg = self.register_desc.allocate_register("temp_audit")
        self.emit_instruction("AUDIT_LOG", f"CREATE_DATABASE:{database_name}", "->", audit_reg)
        
        # 释放临时寄存器
        self.register_desc.free_register(db_reg)
        self.register_desc.free_register(metadata_reg)
        self.register_desc.free_register(permissions_reg)
        self.register_desc.free_register(audit_reg)
        
        self.emit_instruction("CREATE_DB_END", "", "", "")
    
    def _translate_drop_database(self, quad: Quadruple):
        """翻译DROP DATABASE操作"""
        database_name = quad.arg1
        
        # 生成删除数据库指令序列
        self.emit_instruction("; 删除数据库操作")
        self.emit_instruction("DROP_DB_BEGIN", database_name, "", "")
        
        # 为数据库分配寄存器
        db_reg = self.register_desc.allocate_register("temp_database")
        self.emit_instruction("LOAD_DATABASE", database_name, "->", db_reg)
        
        # 检查数据库是否存在
        check_reg = self.register_desc.allocate_register("temp_check")
        self.emit_instruction("CHECK_DB_EXISTS", db_reg, "->", check_reg)
        self.emit_instruction("JZ", "DB_NOT_EXISTS_ERROR", "", "")
        
        # 检查数据库是否正在使用
        usage_reg = self.register_desc.allocate_register("temp_usage")
        self.emit_instruction("CHECK_DB_USAGE", db_reg, "->", usage_reg)
        self.emit_instruction("JNZ", "DB_IN_USE_ERROR", "", "")
        
        # 备份数据库（可选）
        backup_reg = self.register_desc.allocate_register("temp_backup")
        self.emit_instruction("BACKUP_DATABASE", db_reg, "->", backup_reg)
        
        # 删除数据库中的所有表
        self.emit_instruction("DROP_ALL_TABLES", db_reg, "", "")
        
        # 删除数据库元数据
        self.emit_instruction("DELETE_DB_METADATA", db_reg, "", "")
        
        # 删除数据库目录
        self.emit_instruction("DELETE_DB_DIR", database_name, "", "")
        
        # 提交数据库删除
        self.emit_instruction("COMMIT_DROP_DB", db_reg, "", "")
        
        # 生成审计日志
        audit_reg = self.register_desc.allocate_register("temp_audit")
        self.emit_instruction("AUDIT_LOG", f"DROP_DATABASE:{database_name}", "->", audit_reg)
        
        # 释放临时寄存器
        self.register_desc.free_register(db_reg)
        self.register_desc.free_register(check_reg)
        self.register_desc.free_register(usage_reg)
        self.register_desc.free_register(backup_reg)
        self.register_desc.free_register(audit_reg)
        
        self.emit_instruction("DROP_DB_END", "", "", "")
    
    def _translate_list_databases(self, quad: Quadruple):
        """翻译LIST/SHOW DATABASES操作"""
        command = quad.arg1  # 格式: LIST_DATABASES, SHOW_DATABASES, LIST_SCHEMAS, SHOW_SCHEMAS
        
        # 生成列出数据库指令序列
        self.emit_instruction(f"; {command}操作")
        self.emit_instruction("LIST_DB_BEGIN", command, "", "")
        
        # 为结果集分配寄存器
        result_reg = self.register_desc.allocate_register("temp_db_list")
        self.emit_instruction("INIT_DB_LIST", "->", result_reg, "")
        
        # 获取系统中所有数据库
        system_reg = self.register_desc.allocate_register("temp_system")
        self.emit_instruction("GET_SYSTEM_DATABASES", "->", system_reg, "")
        
        # 过滤用户有权限访问的数据库
        filter_reg = self.register_desc.allocate_register("temp_filter")
        self.emit_instruction("FILTER_BY_PERMISSIONS", system_reg, "->", filter_reg)
        
        # 按名称排序数据库列表
        sorted_reg = self.register_desc.allocate_register("temp_sorted")
        self.emit_instruction("SORT_DB_LIST", filter_reg, "->", sorted_reg)
        
        # 格式化输出结果
        format_reg = self.register_desc.allocate_register("temp_format")
        if "DATABASES" in command:
            self.emit_instruction("FORMAT_DB_OUTPUT", sorted_reg, "->", format_reg)
        else:  # SCHEMAS
            self.emit_instruction("FORMAT_SCHEMA_OUTPUT", sorted_reg, "->", format_reg)
        
        # 输出结果
        self.emit_instruction("OUTPUT_DB_LIST", format_reg, "", "")
        
        # 生成审计日志
        audit_reg = self.register_desc.allocate_register("temp_audit")
        self.emit_instruction("AUDIT_LOG", f"{command}:SUCCESS", "->", audit_reg)
        
        # 释放临时寄存器
        self.register_desc.free_register(result_reg)
        self.register_desc.free_register(system_reg)
        self.register_desc.free_register(filter_reg)
        self.register_desc.free_register(sorted_reg)
        self.register_desc.free_register(format_reg)
        self.register_desc.free_register(audit_reg)
        
        self.emit_instruction("LIST_DB_END", "", "", "")
    
    def _translate_create_user(self, quad: Quadruple):
        """翻译CREATE USER操作"""
        username = quad.arg1
        password = quad.arg2  # 可能为"-"表示无密码
        
        # 生成创建用户指令序列
        self.emit_instruction("; 创建用户操作")
        self.emit_instruction("CREATE_USER_BEGIN", username, "", "")
        
        # 为用户分配寄存器
        user_reg = self.register_desc.allocate_register("temp_user")
        self.emit_instruction("INIT_USER", username, "->", user_reg)
        
        # 设置用户基本信息
        self.emit_instruction("SET_USER_NAME", username, user_reg, "")
        
        # 如果有密码，设置密码
        if password != "-":
            password_reg = self.register_desc.allocate_register("temp_password")
            self.emit_instruction("HASH_PASSWORD", password, "->", password_reg)
            self.emit_instruction("SET_USER_PASSWORD", password_reg, user_reg, "")
            self.register_desc.free_register(password_reg)
        
        # 设置用户默认权限
        permissions_reg = self.register_desc.allocate_register("temp_permissions")
        self.emit_instruction("SET_DEFAULT_PERMISSIONS", "CONNECT", "->", permissions_reg)
        self.emit_instruction("APPLY_USER_PERMISSIONS", permissions_reg, user_reg, "")
        
        # 创建用户目录和配置
        self.emit_instruction("CREATE_USER_DIR", username, user_reg, "")
        
        # 提交用户创建
        self.emit_instruction("COMMIT_CREATE_USER", user_reg, "", "")
        
        # 生成审计日志
        audit_reg = self.register_desc.allocate_register("temp_audit")
        self.emit_instruction("AUDIT_LOG", f"CREATE_USER:{username}", "->", audit_reg)
        
        # 释放临时寄存器
        self.register_desc.free_register(user_reg)
        self.register_desc.free_register(permissions_reg)
        self.register_desc.free_register(audit_reg)
        
        self.emit_instruction("CREATE_USER_END", "", "", "")
    
    def _translate_drop_user(self, quad: Quadruple):
        """翻译DROP USER操作"""
        username = quad.arg1
        
        # 生成删除用户指令序列
        self.emit_instruction("; 删除用户操作")
        self.emit_instruction("DROP_USER_BEGIN", username, "", "")
        
        # 为用户分配寄存器
        user_reg = self.register_desc.allocate_register("temp_user")
        self.emit_instruction("LOAD_USER", username, "->", user_reg)
        
        # 检查用户是否存在
        check_reg = self.register_desc.allocate_register("temp_check")
        self.emit_instruction("CHECK_USER_EXISTS", user_reg, "->", check_reg)
        self.emit_instruction("JZ", "USER_NOT_EXISTS_ERROR", "", "")
        
        # 检查用户是否正在使用
        usage_reg = self.register_desc.allocate_register("temp_usage")
        self.emit_instruction("CHECK_USER_SESSIONS", user_reg, "->", usage_reg)
        self.emit_instruction("JNZ", "USER_IN_USE_WARNING", "", "")
        
        # 撤销用户的所有权限
        self.emit_instruction("REVOKE_ALL_PERMISSIONS", user_reg, "", "")
        
        # 删除用户拥有的对象（可选，根据策略）
        self.emit_instruction("DROP_USER_OBJECTS", user_reg, "", "")
        
        # 删除用户配置和目录
        self.emit_instruction("DELETE_USER_DIR", username, "", "")
        
        # 从用户表中删除用户记录
        self.emit_instruction("DELETE_USER_RECORD", user_reg, "", "")
        
        # 提交用户删除
        self.emit_instruction("COMMIT_DROP_USER", user_reg, "", "")
        
        # 生成审计日志
        audit_reg = self.register_desc.allocate_register("temp_audit")
        self.emit_instruction("AUDIT_LOG", f"DROP_USER:{username}", "->", audit_reg)
        
        # 释放临时寄存器
        self.register_desc.free_register(user_reg)
        self.register_desc.free_register(check_reg)
        self.register_desc.free_register(usage_reg)
        self.register_desc.free_register(audit_reg)
        
        self.emit_instruction("DROP_USER_END", "", "", "")
    
    def _translate_list_users(self, quad: Quadruple):
        """翻译LIST/SHOW USERS操作"""
        command = quad.arg1  # 格式: LIST_USERS, SHOW_USERS
        
        # 生成列出用户指令序列
        self.emit_instruction(f"; {command}操作")
        self.emit_instruction("LIST_USERS_BEGIN", command, "", "")
        
        # 为结果集分配寄存器
        result_reg = self.register_desc.allocate_register("temp_user_list")
        self.emit_instruction("INIT_USER_LIST", "->", result_reg, "")
        
        # 获取系统中所有用户
        system_reg = self.register_desc.allocate_register("temp_system")
        self.emit_instruction("GET_SYSTEM_USERS", "->", system_reg, "")
        
        # 过滤当前用户有权限查看的用户
        filter_reg = self.register_desc.allocate_register("temp_filter")
        self.emit_instruction("FILTER_USER_BY_PERMISSIONS", system_reg, "->", filter_reg)
        
        # 按用户名排序用户列表
        sorted_reg = self.register_desc.allocate_register("temp_sorted")
        self.emit_instruction("SORT_USER_LIST", filter_reg, "->", sorted_reg)
        
        # 格式化输出结果
        format_reg = self.register_desc.allocate_register("temp_format")
        self.emit_instruction("FORMAT_USER_OUTPUT", sorted_reg, "->", format_reg)
        
        # 输出结果
        self.emit_instruction("OUTPUT_USER_LIST", format_reg, "", "")
        
        # 生成审计日志
        audit_reg = self.register_desc.allocate_register("temp_audit")
        self.emit_instruction("AUDIT_LOG", f"{command}:SUCCESS", "->", audit_reg)
        
        # 释放临时寄存器
        self.register_desc.free_register(result_reg)
        self.register_desc.free_register(system_reg)
        self.register_desc.free_register(filter_reg)
        self.register_desc.free_register(sorted_reg)
        self.register_desc.free_register(format_reg)
        self.register_desc.free_register(audit_reg)
        
        self.emit_instruction("LIST_USERS_END", "", "", "")
    
    def _print_results(self):
        """打印生成结果"""
        print("\n=== 目标代码生成结果 ===")
        
        # 打印目标代码
        print("\n生成的目标代码:")
        for i, instruction in enumerate(self.target_code):
            print(f"{i:3d}: {instruction}")
        
        # 打印寄存器分配情况
        print(f"\n寄存器分配情况:")
        print(f"{'寄存器':<8} {'存储的变量':<20}")
        print("-" * 30)
        for reg, vars in self.register_desc.register_contents.items():
            var_list = ', '.join(vars) if vars else "空闲"
            print(f"{reg:<8} {var_list:<20}")
        
        # 打印内存分配情况
        print(f"\n变量内存分配:")
        if self.variable_memory:
            print(f"{'变量名':<15} {'内存地址':<10}")
            print("-" * 25)
            for var, addr in sorted(self.variable_memory.items()):
                print(f"{var:<15} {addr:<10}")
        else:
            print("无变量内存分配")
        
        # 打印错误信息
        if self.errors:
            print("\n目标代码生成错误:")
            for error in self.errors:
                print(f"  {error}")
        else:
            print("\n✓ 目标代码生成成功，无错误")


def get_output_mode():
    """获取用户选择的输出模式"""
    print("\n=== SQL编译器 - 输出模式选择 ===")
    print("请选择要显示的编译阶段：")
    print("0 - 只显示编译结果（通过/失败）")
    print("1 - 词法分析过程")
    print("2 - 语法分析过程") 
    print("3 - 语义分析过程")
    print("4 - 目标代码生成过程")
    print("\n可以组合使用，用空格分隔，例如：")
    print("  '1 3' - 显示词法分析和语义分析过程")
    print("  '2 4' - 显示语法分析和目标代码生成过程")
    print("  '1 2 3 4' - 显示所有编译过程")
    
    while True:
        try:
            choice = input("\n请输入选择（默认为0）: ").strip()
            if not choice:
                return {0}
            
            # 解析用户输入
            modes = set()
            for part in choice.split():
                mode = int(part)
                if mode not in [0, 1, 2, 3, 4]:
                    print(f"错误：'{mode}' 不是有效选项，请输入0-4之间的数字")
                    break
                modes.add(mode)
            else:
                return modes
                
        except ValueError:
            print("错误：请输入有效的数字")


def run_compilation_with_error_correction(sql_statement, output_modes, lexical_analyzer, 
                                        syntax_analyzer, semantic_analyzer, code_generator, 
                                        is_first_run=False, show_corrections=True):
    """
    运行带智能纠错的编译过程
    
    Args:
        sql_statement: SQL语句
        output_modes: 输出模式集合
        is_first_run: 是否是第一次运行（需要构建语法分析表）
        show_corrections: 是否显示纠错信息
    """
    # 存储编译结果
    results = {
        'lexical': False,
        'syntax': False, 
        'semantic': False,
        'code_gen': False,
        'errors': [],
        'corrections': {
            'lexical': '',
            'syntax': '',
            'semantic': ''
        }
    }
    
    # 1. 词法分析
    try:
        tokens = lexical_analyzer.analyze(sql_statement)
        
        # 检查词法分析是否有错误
        if lexical_analyzer.has_errors():
            results['lexical'] = False
            results['errors'].append("词法分析发现错误")
        else:
            results['lexical'] = True
        
        if 1 in output_modes:
            print("\n=== 词法分析过程 ===")
            print("词法分析结果:")
            for token in tokens:
                if token.type.name != 'EOF':
                    print(f"  {token}")
        
        # 收集词法分析的纠错信息（但不立即显示）
        if show_corrections and lexical_analyzer.has_errors():
            results['corrections']['lexical'] = lexical_analyzer.get_error_report()
        
        # 如果词法分析有错误，直接返回
        if not results['lexical']:
            return results
        
    except Exception as e:
        results['errors'].append(f"词法分析错误: {e}")
        if 1 in output_modes:
            print(f"\n❌ 词法分析失败: {e}")
        return results
    
    # 2. 语法分析
    try:
        if 2 in output_modes:
            # 显示语法分析过程
            if is_first_run:
                syntax_result = syntax_analyzer.analyze(tokens)
            else:
                syntax_result = syntax_analyzer.predictive_parse(tokens)
        else:
            # 静默执行语法分析
            import io
            import sys
            old_stdout = sys.stdout
            sys.stdout = io.StringIO()
            
            try:
                if is_first_run:
                    syntax_result = syntax_analyzer.analyze(tokens)
                else:
                    syntax_result = syntax_analyzer.predictive_parse(tokens)
            finally:
                sys.stdout = old_stdout
        
        results['syntax'] = syntax_result
        
        # 收集语法分析的纠错信息（但不立即显示）
        if show_corrections and syntax_analyzer.has_errors():
            results['corrections']['syntax'] = syntax_analyzer.get_error_report()
            # 存储修复建议
            correction_suggestions = syntax_analyzer.get_correction_suggestions()
            if correction_suggestions:
                results['corrections']['syntax'] += "\n" + correction_suggestions
        
        if 2 in output_modes and syntax_result:
            print("\n✅ 语法分析成功")
        elif 2 in output_modes and not syntax_result:
            print("\n❌ 语法分析失败")
            
    except Exception as e:
        results['errors'].append(f"语法分析错误: {e}")
        if 2 in output_modes:
            print(f"\n❌ 语法分析异常: {e}")
        return results
    
    if not results['syntax']:
        if 2 not in output_modes:
            results['errors'].append("语法分析失败")
        return results
    
    # 3. 语义分析
    try:
        if 3 in output_modes:
            quadruples, symbol_table, semantic_errors = semantic_analyzer.analyze(tokens)
        else:
            # 静默版本的语义分析
            import io
            import sys
            old_stdout = sys.stdout
            sys.stdout = io.StringIO()
            
            try:
                quadruples, symbol_table, semantic_errors = semantic_analyzer.analyze(tokens)
            finally:
                sys.stdout = old_stdout
        
        if not semantic_errors:
            results['semantic'] = True
            if 3 in output_modes:
                print("\n✅ 语义分析成功")
        else:
            results['errors'].extend([f"语义分析错误: {error}" for error in semantic_errors])
            if 3 in output_modes:
                print(f"\n❌ 语义分析失败")
                for error in semantic_errors:
                    print(f"  {error}")
        
        # 收集语义分析的纠错信息（但不立即显示）
        if show_corrections and semantic_analyzer.has_errors():
            results['corrections']['semantic'] = semantic_analyzer.get_error_report()
            # 存储修复建议
            correction_suggestions = semantic_analyzer.get_correction_suggestions()
            if correction_suggestions:
                results['corrections']['semantic'] += "\n" + correction_suggestions
        
        if semantic_errors:
            return results
            
    except Exception as e:
        results['errors'].append(f"语义分析异常: {e}")
        if 3 in output_modes:
            print(f"\n❌ 语义分析异常: {e}")
        return results
    
    # 4. 目标代码生成
    try:
        if 4 in output_modes:
            target_code, code_errors = code_generator.generate_code(quadruples, symbol_table)
        else:
            # 静默版本的代码生成
            import io
            import sys
            old_stdout = sys.stdout
            sys.stdout = io.StringIO()
            
            try:
                target_code, code_errors = code_generator.generate_code(quadruples, symbol_table)
            finally:
                sys.stdout = old_stdout
        
        if not code_errors:
            results['code_gen'] = True
            if 4 in output_modes:
                print("\n✅ 目标代码生成成功")
        else:
            results['errors'].extend([f"代码生成错误: {error}" for error in code_errors])
            if 4 in output_modes:
                print(f"\n❌ 目标代码生成失败")
                for error in code_errors:
                    print(f"  {error}")
                    
    except Exception as e:
        results['errors'].append(f"代码生成异常: {e}")
        if 4 in output_modes:
            print(f"\n❌ 代码生成异常: {e}")
    
    return results


def run_compilation(sql_statement, output_modes, lexical_analyzer, syntax_analyzer, 
                   semantic_analyzer, code_generator, is_first_run=False):
    """
    运行编译过程（默认启用智能纠错）
    """
    return run_compilation_with_error_correction(
        sql_statement, output_modes, lexical_analyzer, syntax_analyzer,
        semantic_analyzer, code_generator, is_first_run, show_corrections=True
    )


def main():
    """测试主函数"""
    from LexicalAnalysis import LexicalAnalyzer
    from SyntaxAnalysis import SyntaxAnalyzer
    from SemanticAnalysis import SemanticAnalyzer
    
    # 创建分析器实例（启用测试模式）
    lexical_analyzer = LexicalAnalyzer()
    syntax_analyzer = SyntaxAnalyzer()
    semantic_analyzer = SemanticAnalyzer(use_test_data=True)  # 启用测试模式
    code_generator = CodeGenerator()
    
    # 获取用户选择的输出模式
    output_modes = get_output_mode()
    
    # 是否显示纠错信息
    show_corrections = True
    
    # 测试SQL语句集合
    test_cases = [
        # # =========================
        # # 1. 数据库管理语句测试
        # # =========================
        # "CREATE DATABASE new_test_db;",        # 创建数据库
        # "USE test_db;",                        # 切换数据库
        # "DROP DATABASE test_db;",              # 删除数据库
        # "LIST DATABASES;",                     # 列出所有数据库
        # "SHOW DATABASES;",                     # 显示所有数据库
        # "LIST SCHEMAS;",                       # 列出所有模式
        # "SHOW SCHEMAS;",                       # 显示所有模式              
        
        # # =========================
        # # 2. 用户管理语句测试
        # # =========================
        # "CREATE USER user_test;",               # 创建用户（无密码）
        # "CREATE USER user_test1 IDENTIFIED BY 'password123';",  # 创建用户（有密码）
        # "DROP USER old_user;",                 # 删除用户
        # "LIST USERS;",                         # 列出所有用户
        # "SHOW USERS;",                         # 显示所有用户
        
        # # =========================
        # # 3. 表结构操作语句测试
        # # =========================
        # "CREATE TABLE Students (id INT, name VARCHAR(50), age INT, major VARCHAR(30));",  # 创建表
        # "DROP TABLE Students;",                # 删除表
        # "CREATE TABLE test_table (id INT, name VARCHAR(50), score INT);",   # 创建另一个表
        
        # # =========================
        # # 4. 基本查询语句测试
        # # =========================
        # "SELECT * FROM Students;",             # 查询所有列
        # "SELECT name FROM Students;",          # 查询单列
        # "SELECT id, name, age FROM Students;", # 查询多列
        # "SELECT name, age FROM Students;",     # 查询指定列
        
        # # =========================
        # # 5. 条件查询语句测试
        # # =========================
        # "SELECT name FROM Students WHERE age > 18;",              # 简单WHERE条件
        # "SELECT * FROM Students WHERE major = 'CS';",             # 字符串等值查询
        # "SELECT name FROM Students WHERE age >= 20 AND age <= 25;", # 范围查询
        # "SELECT * FROM Students WHERE age != 22;",                # 不等于查询
        
        # # =========================
        # # 6. 逻辑操作符测试
        # # =========================
        # "SELECT name FROM Students WHERE age > 18 AND major = 'CS';",  # 简单AND条件
        # "SELECT name FROM Students WHERE age < 25 OR age > 65;",       # 简单OR条件
        # "SELECT * FROM Students WHERE age > 18 AND age < 25 AND major = 'CS';",  # 多个AND
        # "SELECT * FROM Students WHERE major = 'CS' OR major = 'Math' OR major = 'Physics';",  # 多个OR
        # "SELECT name FROM Students WHERE (age > 18 AND age < 25) OR major = 'CS';",  # 括号表达式
        # "SELECT * FROM Students WHERE age > 20 AND (major = 'CS' OR major = 'Math');",  # 混合AND/OR
        
        # # =========================
        # # 7. LIKE模式匹配测试
        # # =========================
        # "SELECT name FROM Students WHERE name LIKE 'John%';",     # LIKE与%通配符
        # "SELECT * FROM Students WHERE name LIKE '_ohn';",         # LIKE与_通配符
        # "SELECT name FROM Students WHERE major LIKE '%CS%';",     # LIKE包含匹配
        # "SELECT * FROM Students WHERE name LIKE 'A%' AND major LIKE '%Science';",  # LIKE与AND
        # "SELECT name FROM Students WHERE name LIKE 'John%' OR name LIKE 'Jane%';", # LIKE与OR
        
        # # =========================
        # # 8. 排序和限制语句测试
        # # =========================
        # "SELECT name, age FROM Students ORDER BY age;",           # 基本排序
        # "SELECT name, age FROM Students ORDER BY age DESC;",      # 降序排序
        # "SELECT name, age FROM Students ORDER BY age ASC, name DESC;",  # 多列排序
        # "SELECT id, name FROM Students LIMIT 5;",                 # 限制结果数量
        # "SELECT name FROM Students WHERE major='CS' LIMIT 3;",    # 条件查询 + 限制
        # "SELECT name, age FROM Students ORDER BY age DESC LIMIT 1;",  # 排序 + 限制
        
        # # =========================
        # # 9. 聚合函数测试
        # # =========================
        # "SELECT COUNT(*) FROM Students;",                         # COUNT(*) 基本用法
        # "SELECT COUNT(name) FROM Students;",                      # COUNT(column) 基本用法
        # "SELECT SUM(age) FROM Students;",                         # SUM 函数
        # "SELECT AVG(age) FROM Students;",                         # AVG 函数
        # "SELECT MAX(age), MIN(age) FROM Students;",               # MAX 和 MIN 函数
        # "SELECT COUNT(*), AVG(age) FROM Students WHERE major = 'CS';",  # 聚合函数与WHERE子句
        
        # # =========================
        # # 10. 分组查询测试
        # # =========================
        # "SELECT major, COUNT(*) FROM Students GROUP BY major;",   # 基本GROUP BY
        # "SELECT major, AVG(age) FROM Students GROUP BY major;",   # GROUP BY与聚合函数
        # "SELECT major, COUNT(*) FROM Students GROUP BY major HAVING COUNT(*) > 5;", # GROUP BY与HAVING
        
        # # =========================
        # # 11. 连接查询测试
        # # =========================
        # "SELECT s.name, c.name FROM Students s JOIN Courses c ON s.id = c.id;",  # 内连接
        # "SELECT s.name, c.name FROM Students s LEFT JOIN Courses c ON s.id = c.id;", # 左连接
        # "SELECT s.name, c.name FROM Students s RIGHT JOIN Courses c ON s.id = c.id;", # 右连接
        # "SELECT s.name, c.name FROM Students s FULL OUTER JOIN Courses c ON s.id = c.id;", # 全外连接
        
        # # =========================
        # # 12. 集合操作测试
        # # =========================
        # "SELECT name FROM Students UNION SELECT name FROM Teachers;",     # UNION基本用法
        # "SELECT id, name FROM Students UNION ALL SELECT id, name FROM Teachers;",  # UNION ALL
        # "SELECT name FROM Students WHERE age > 20 UNION SELECT name FROM Teachers WHERE age < 60;",  # 条件UNION
        # "SELECT name, age FROM Students UNION SELECT name, age FROM Teachers ORDER BY name;",  # UNION排序
        
        # # =========================
        # # 13. 数据修改语句测试
        # # =========================
        # "INSERT INTO Students (id, name, age, major) VALUES (1, 'John', 20, 'CS');",  # 基本插入
        # "UPDATE Students SET age = 21 WHERE id = 1;",                     # 基本更新
        # "UPDATE Students SET age = 22, major = 'Physics' WHERE name = 'John';",  # 多列更新
        # "DELETE FROM Students WHERE age > 60;",                           # 基本删除
        # "DELETE FROM Students WHERE age > 60 AND name = 'John';",         # 条件删除
        
        # # =========================
        # # 14. 权限管理语句测试
        # # =========================
        # "GRANT SELECT ON Students TO alice;",                             # 基本GRANT语句
        # "GRANT SELECT, INSERT ON TABLE Students TO alice, bob;",          # 多权限、多用户
        # "GRANT SELECT ON DATABASE hr_system TO USER alice;",                # 数据库级权限
        # "GRANT UPDATE ON Students TO ROLE admin_role;",                   # 角色权限
        # "GRANT SELECT ON Students TO alice WITH GRANT OPTION;",           # 带GRANT OPTION
        # "GRANT ALL PRIVILEGES ON DATABASE hr_system TO USER manager;",    # 完整语法
        # "GRANT ALL ON Students TO PUBLIC;",                               # 授予所有权限给公共用户
        
        # # =========================
        # # 15. 复杂查询测试
        # # =========================
        # "SELECT s.name, s.age, COUNT(c.course_id) FROM Students s LEFT JOIN Courses c ON s.id = c.course_id GROUP BY s.name, s.age;",  # 连接+分组
        # "SELECT major, AVG(age) FROM Students WHERE age > 18 GROUP BY major HAVING AVG(age) > 20 ORDER BY AVG(age) DESC;",  # 复合查询
        # "SELECT name FROM Students WHERE age > (SELECT AVG(age) FROM Students);",  # 子查询（简化）
        
        # =========================
        # 16. 专门的智能纠错测试用例
        # =========================
        # 语法错误类
        "SELECT FROM Student_test;",                        # 缺少选择列表
        "SELECT name_test FROM;",                           # 缺少表名
        "SELECT name Students;",                       # 缺少From
        "SELECT name_test FROM Students_test WHERE;",            # WHERE子句不完整
        "SELECT name_test FROM Students_test WHERE age_test > 18 AND;",  # AND后缺少条件
        "SELECT name_test FROM Students_test WHERE OR age_test < 25;",   # OR前缺少条件
        "CREATE TABLE Students_test (id_test INT name_test VARCHAR(50));",  # 缺少逗号分隔符
        "DROP Students_test;",                              # 缺少TABLE关键字
        "DROP TABLE;",                                 # 缺少表名
        "UPDATE Students_test SET WHERE id_test = 1;",           # SET子句不完整
        "DELETE Students_test WHERE age_test > 60;",             # 缺少FROM关键字
        "SELECT name, FROM Students;",                               # 多余的逗号
        "SELECT name FROM Students WHERE age > 18;;",                # 多余的分号
        
        # 词法错误类
        "SELECT name FROM Students WHERE age > 18 @ major = 'CS';",  # 非法字符
        "SELECT name FROM Students WHERE age >= 20 && age <= 25;",   # 错误的操作符
        "SELECT name FROM Students WHERE major == 'CS';",            # 错误的等号操作符
        
         
        # 语义错误类（应该失败但有智能纠错）
        "SELECT unknown_column FROM Students;",       # 不存在的列名
        "SELECT name FROM UnknownTable;",             # 不存在的表名
        "SELECT unknown_column FROM UnknownDatabase;",# 不存在的数据库
        "DROP TABLE UnknownTable;",                   # 删除不存在的表
        "DROP USER unknown_user;",                    # 删除不存在的用户
        
        # 拼写错误类
        "SELCT name FROM Students;",                  # SELECT拼写错误
        "SELECT name FORM Students;",                 # FROM拼写错误
        "SELECT name FROM Students WERE age > 18;",   # WHERE拼写错误
        "CREAT TABLE Test (id INT);",                 # CREATE拼写错误
        "INSRT INTO Students VALUES (1, 'John');",    # INSERT拼写错误
        "UPDAT Students SET age = 21;",               # UPDATE拼写错误
        "DELET FROM Students WHERE age > 60;",        # DELETE拼写错误
        "GRAN SELECT ON Students TO alice;",          # GRANT拼写错误
        
        # 标点符号错误类
        "SELECT name FROM Students WHERE age > 18",   # 缺少分号
        "SELECT name, age, FROM Students;",           # 多余的逗号
        
        # 关键字使用错误类
        "SELECT SELECT FROM Students;",               # 重复关键字
        "SELECT name FROM Students WHERE WHERE age > 18;",  # 重复WHERE
        "CREATE CREATE TABLE Test (id INT);",         # 重复CREATE
        "SELECT name FROM Students ORDER ORDER BY age;",    # 重复ORDER
        "SELECT name FROM Students GROUP GROUP BY major;",  # 重复GROUP
        
        # # =========================
        # # 17. 谓词下推优化测试用例
        # # =========================
        # "SELECT name, age FROM Students WHERE age > 20;",              # 简单谓词下推
        # "SELECT * FROM Students WHERE age > 18 AND major = 'CS';",     # 复合条件谓词下推
        # "SELECT s.name, t.name FROM Students s JOIN Teachers t ON s.id = t.id WHERE s.age > 25;",  # JOIN谓词下推
        # "SELECT s.name, c.name FROM Students s LEFT JOIN Courses c ON s.id = c.id WHERE s.age > 20 AND c.credits > 3;",  # 复杂JOIN谓词下推
    ]
    
    print(f"\n{'='*80}")
    print("SQL编译器测试开始")
    print(f"输出模式: {sorted(output_modes)}")
    print(f"{'='*80}")
    
    # 编译结果统计
    total_tests = len(test_cases)
    passed_tests = 0
    
    for i, test_sql in enumerate(test_cases, 1):
        print(f"\n{'='*70}")
        print(f"测试用例 {i}: {test_sql}")
        print('='*70)
        
        # 运行编译过程（默认启用智能纠错）
        results = run_compilation_with_error_correction(
            test_sql, output_modes, lexical_analyzer, syntax_analyzer,
            semantic_analyzer, code_generator, is_first_run=(i == 1), show_corrections=True
        )
        
        # 显示编译结果
        if 0 in output_modes or len(output_modes) == 1:
            print(f"\n编译结果:")
            if results['lexical']:
                print("  ✅ 词法分析：通过")
            else:
                print("  ❌ 词法分析：失败")
                
            if results['syntax']:
                print("  ✅ 语法分析：通过")
            else:
                print("  ❌ 语法分析：失败")
                
            if results['semantic']:
                print("  ✅ 语义分析：通过")
            else:
                print("  ❌ 语义分析：失败")
                
            if results['code_gen']:
                print("  ✅ 目标代码生成：通过")
            else:
                print("  ❌ 目标代码生成：失败")
        
        # 在编译结果之后显示智能纠错报告
        if show_corrections:
            any_corrections = any(results['corrections'][stage].strip() for stage in results['corrections'])
            if any_corrections:
                # 使用智能纠错系统进行分析
                smart_corrector = SmartErrorCorrector()
                
                # 收集所有错误信息
                all_errors = []
                parse_errors = []
                semantic_errors = []
                
                # 提取各阶段的错误
                for stage_name, stage_key in [("词法分析", "lexical"), ("语法分析", "syntax"), ("语义分析", "semantic")]:
                    if results['corrections'][stage_key].strip():
                        error_content = results['corrections'][stage_key]
                        lines = error_content.split('\n')
                        for line in lines:
                            line = line.strip()
                            if line and ('错误' in line or 'ERROR' in line or '第' in line or '无法处理' in line):
                                if stage_key == 'syntax':
                                    # 只添加真正的语法错误
                                    if not line.startswith('语义错误'):
                                        parse_errors.append(line)
                                elif stage_key == 'semantic':
                                    # 只添加真正的语义错误
                                    if line.startswith('语义错误') or '不存在' in line or '已存在' in line:
                                        semantic_errors.append(line)
                
                # 分析各类错误
                try:
                    # 创建模拟的tokens用于词法分析
                    mock_tokens = []
                    words = test_sql.replace(';', ' ; ').replace(',', ' , ').split()
                    for word_idx, word in enumerate(words):
                        if word.upper() not in smart_corrector.sql_keywords and len(word) > 1 and word not in [';', ',', '(', ')']:
                            # 创建模拟token用于拼写检查
                            class MockTokenType:
                                def __init__(self, name):
                                    self.name = name
                            
                            class MockToken:
                                def __init__(self, token_type, value, line, column):
                                    self.type = token_type
                                    self.value = value
                                    self.line = line
                                    self.column = column
                            
                            mock_tokens.append(MockToken(MockTokenType('IDENTIFIER'), word, 1, word_idx * 10))
                    
                    # 分析词法错误
                    lexical_errors = smart_corrector.analyze_lexical_errors(test_sql, mock_tokens)
                    all_errors.extend(lexical_errors)
                    
                    # 分析语法错误
                    syntax_errors = smart_corrector.analyze_syntax_errors(test_sql, parse_errors)
                    all_errors.extend(syntax_errors)
                    
                    # 分析语义错误（使用预定义的表和数据库）
                    predefined_tables = {
                        'Students': ['id', 'name', 'age', 'major'],
                        'Teachers': ['id', 'name', 'department'],
                        'Courses': ['id', 'course_name', 'teacher_id']
                    }
                    predefined_databases = {'test_db', 'demo_db', 'hr_system'}
                    
                    semantic_error_analysis = smart_corrector.analyze_semantic_errors(
                        semantic_errors, predefined_tables, predefined_databases
                    )
                    all_errors.extend(semantic_error_analysis)
                    
                    # 将错误添加到纠错器
                    for error in all_errors:
                        smart_corrector.add_error(error)
                    
                    # 显示智能纠错报告
                    error_report = smart_corrector.format_error_report()
                    if error_report and "未发现错误" not in error_report:
                        print(error_report)
                
                except Exception as e:
                    # 如果智能纠错系统出错，回退到基本错误显示
                    print(f"\n🔍 智能纠错报告")
                    print("=" * 50)
                    print(f"\n⚠️ 智能纠错系统异常: {e}")
                    print(f"\n❌ 发现的问题:")
                    
                    # 提取基本错误信息
                    found_errors = False
                    for stage_name, stage_key in [("词法分析", "lexical"), ("语法分析", "syntax"), ("语义分析", "semantic")]:
                        if results['corrections'][stage_key].strip():
                            error_content = results['corrections'][stage_key]
                            lines = error_content.split('\n')
                            for line in lines:
                                if line.strip() and ('错误' in line or 'ERROR' in line or '第' in line or '无法处理' in line):
                                    print(f"  [{stage_name}] {line.strip()}")
                                    found_errors = True
                    
        
        # 最终结果
        if all([results['lexical'], results['syntax'], results['semantic'], results['code_gen']]):
            print(f"\n🎉 测试用例 {i} 编译成功！")
            passed_tests += 1
        else:
            print(f"\n💥 测试用例 {i} 编译失败")
            if results['errors']:
                print("错误信息:")
                for error in results['errors']:
                    print(f"  • {error}")
    
    # 总结
    print(f"\n{'='*80}")
    print(f"测试总结: {passed_tests}/{total_tests} 通过")
    print(f"成功率: {passed_tests/total_tests*100:.1f}%")
    print(f"{'='*80}")


if __name__ == "__main__":
    main()
